package com.it.nongchanping.controller;

import com.it.nongchanping.entity.News;
import com.it.nongchanping.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/news")
public class AdminNewsController {

    @Autowired
    private NewsService newsService;

    @GetMapping("")
    public String listNews(Model model) {
        List<News> newsList = newsService.getAllNews();
        model.addAttribute("newsList", newsList);
        model.addAttribute("title", "新闻管理");
        model.addAttribute("activePage", "news");
        return "admin/news/list";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("news", new News());
        model.addAttribute("title", "添加新新闻");
        model.addAttribute("activePage", "news");
        return "admin/news/form";
    }

    @PostMapping("/save")
    public String saveNews(@ModelAttribute News news, RedirectAttributes redirectAttributes) {
        boolean success;
        if (news.getId() == null) {
            success = newsService.saveNews(news);
        } else {
            success = newsService.updateNews(news);
        }
        
        if (success) {
            redirectAttributes.addFlashAttribute("message", "新闻保存成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "新闻保存失败！");
        }
        return "redirect:/admin/news";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        News news = newsService.getNewsById(id);
        model.addAttribute("news", news);
        model.addAttribute("title", "编辑新闻");
        model.addAttribute("activePage", "news");
        return "admin/news/form";
    }

    @GetMapping("/delete/{id}")
    public String deleteNews(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        if (newsService.deleteNews(id)) {
            redirectAttributes.addFlashAttribute("message", "新闻删除成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "新闻删除失败！");
        }
        return "redirect:/admin/news";
    }
} 